<?php
chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";



class SalesReportingList extends IPlugin 
{
    var $color;
    
    function SalesReportingList($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
        $this->color = "blue";
    }
    
    function getPluginTag() { return "SalesReportingList"; }
    function getPluginName() { return "Sales Reporting List Plugin"; }
    function getPluginVersion() { return "1.0.0"; }
    
    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuTitle", "MenuBlockTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Shopping cart"; } break;
            case "MenuTitle" : { return "Sales Reporting"; } break;
        };
        return $result;
    }
    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------
    function doAction($params)
    {
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;
        }
        $arg = getCoreInstance();
        $arg = $arg->getGET();
        
        if("doApplyDates" == $_POST["action"])
        {
            $z = $_POST;
            $uid = $z["id"];
            
        }
    }


    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function Render($params)
    {
        global $_G;
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }
        
        $core = getCoreInstance();
        $render = $core->framework->smarty;
        $render->assign("baseurl", "?".$this->getURL()."&page=".$_G["page"]);

        $page = "";

        switch ($_G["page"]) {
            
            default:
                $page = $this->renderSalesReportingList($render);
                break;
        }
        return $render->fetch("file:".$this->tplfolder."/".$page);
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Generate CProduct List ] --------------------------------------------------
    // ----------------------------------------------------------------------------------
    
    function cb_renderCT($data)
    {
        $dt = array(
                array("<a style=\"text-decoration:none;\" title=\"click for view details\" href=\"?path=orderslist,productlist&page=edit&id=$data[catalogid]\">$data[title]</a>" , ""),
                array("$ ".number_format($data["price"], 2, '.', ' ') , "align=\"center\""),
                array($data['qty'] , "align='center'"),
                array("$ ".number_format($data["total_price"], 2, '.', ' '), "align='center'"),
                );
        return $dt;
    }
    function renderSalesReportingList(&$render)
    {
        $core = &getCoreInstance();
        $db = $core->getProperty("db");
        
        $startDate = $_REQUEST['startDate'];
        $endDate = $_REQUEST['endDate'];
        $where_date = "";
        $dates_params = ""; // params for print url
        if(isne($startDate))
        {
            $render->assign('start_date',$startDate);
            $timest = getdate(strtotime($startDate));
            $gm = gmdate ("Y-m-d H:i:s",$timest[0]);
            $where_date .= " and pubdate >= '{$gm}' " ;
            $dates_params .="&startDate=".$startDate;
        }
        if(isne($endDate))
        {
            $render->assign('end_date',$endDate);
            $timest = getdate(strtotime($endDate));
            $gm = gmdate ("Y-m-d H:i:s",$timest[0]);
            $where_date .= " and pubdate <= '{$gm}' ";
            $dates_params .="&endDate=".$endDate;
        }
        if (isne($endDate) or isne($startDate))
            $dates_params .="&";
        //
        
        $pg = &$core->getSnippet("paginator");
        $tmp_url = $this->getURL()."&catalog_id=".$_REQUEST['catalog_id'];
        $page = $ppg = -1; /// curent count page
        // ============== list 1    [
        $array=$db->getall("select catalogid,title,sum(p.price) as price,sum(qty) as qty,sum((p.price * qty)) as total_price from purchaseitems p, orders o where p.order_id = o.id  and status = 3 and type_order='ord' " .$where_date."  group by catalogid ORDER BY order_id");
        $params = array(
                    "cb_class" => &$this,
                    "cb_func" => cb_renderCT,
                    "urlbase" => $tmp_url,
                    "caption" => "Sales Reporting List by purchased items",
                    "emptymsg" => "<center>No such items</center>",
                    "header" => array("Product","Price","Quantity", "Total price"),
                    "items" => "",  
                    "source" => "array", // -- sql, array
                    "items" => $array,
                    "ippg" => 10, // -- items per page
                    "nppv" => 5, // -- number pages per view
                    "page" => &$page,
                    "ppg" => &$ppg,
                    
                    );

        $HTML = $pg->Render($params);
        $render->assign("productlist1", $HTML);
        // ============== list 1    ]
        // ============== list 2   [
        $array=$db->getall("select catalogid,title,sum(p.price) as price,sum(qty) as qty,sum((p.price * qty)) as total_price from purchaseitems p, orders o where p.order_id = o.id  and status = 3 and type_order='ret' " .$where_date."  group by catalogid ORDER BY order_id");
        $params = array(
                    "cb_class" => &$this,
                    "cb_func" => cb_renderCT,
                    "urlbase" => $tmp_url,
                    "caption" => "Sales Reporting List by returned items",
                    "emptymsg" => "<center>No such items</center>",
                    "header" => array("Product","Price","Quantity", "Total price"),
                    "items" => "",  
                    "source" => "array", // -- sql, array
                    "items" => $array,
                    "ippg" => 10, // -- items per page
                    "nppv" => 5, // -- number pages per view
                    "page" => &$page,
                    "ppg" => &$ppg,
                    
                    );
        $HTML = $pg->Render($params);
        $render->assign("productlist2", $HTML);
        // ============== list 2   ]
        $total_sql = "select sum(qty) as qty,sum((p.price * qty)) as total_price from purchaseitems p, orders o where p.order_id = o.id and status = 3 ".$where_date;
        $total_res = $db->getAll($total_sql);
        $render->assign("total_items", $total_res[0]['qty']);
        $render->assign("total_price", " ".number_format($total_res[0]['total_price'], 2, '.', ' '));
        $render->assign("showCloseButton", 1);
        $render->assign("print_url", "?".$this->getURL()."&doPrint=doPrint&showCloseButton=1&{$dates_params}st_paginator_page=-1");
        
        if( isne($_GET['doPrint']) )
            $render->assign("visible_print", "false");
            
        $render->assign("url", "?".$this->getURL());
        
        return "salesreportinglist.tpl.php";
    }/// renderSalesList
    

};


?>